<?php
namespace Modules\Api\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Bill;
use App\Models\Order;
use App\Models\OrderGoods;
use App\Models\Recharge;
use App\Models\RechargeOrder;
use App\Models\System;
use App\Models\User;
use App\Models\UserScoreRecord;
use App\Models\Wxpay;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Yansongda\Pay\Pay;

class PayController extends Controller{
    //支付回调
    public function notify(){
        Log::info("进入回调");
        //获取支付信息
        $wechat = Wxpay::wxPay();

        $pay = Pay::wechat($wechat);

        try{
            $data = $pay->verify(); // 是的，验签就这么简单！
            //获取订单号
            $order_sn = $data['out_trade_no'];
            //订单支付金额
            $total_fee = $data['total_fee'];
            //支付流水
            $transaction_id = $data['transaction_id'];

            //判断订单号
            $header = substr($order_sn,0,2);
            if ($header!='CZ') {
                //查询订单
                $order = Order::where("order_sn", $order_sn)->first();
                //判断订单支付金额是否等于实际支付金额
                if ($order->pay_amount != $total_fee / 100) {
                    $refund = Wxpay::refundPay();
                    //退款
                    $order = [
                        'transaction_id' => $transaction_id,
                        'out_refund_no' => $order_sn,
                        'total_fee' => $total_fee, // **单位：分**
                        'refund_fee' => $total_fee,
                        "type" => 'miniapp',
                        'refund_desc' => '微信支付退款'
                    ];
                    //调用支付
                    Pay::wechat($refund)->refund($order);
                } else {
                    DB::beginTransaction();
                    //修改订单状态
                    $order->order_status = 1;
                    $order->pay_time = Carbon::now();
                    $order->save();
                    //修改支付记录
                    $ment = Wxpay::where("pay_sn", $order_sn)->first();
                    $ment->is_paid = 1;
                    $ment->transaction_id = $transaction_id;
                    $ment->amount = $total_fee / 100;
                    $ment->paid_at = Carbon::now();
                    $ment->save();
                    //商品增加销量
                    $goods = OrderGoods::where("order_id",$order->id)->with("goods")->get();
                    if ($goods->count()>0){
                        foreach ($goods as $item){
                            $item->goods->sell_num = $item->goods->sell_num+$item->goods_num;
                            $item->goods->save();
                        }
                    }

                    //商品规格增加销量
                    $sku = OrderGoods::wehre("order_id",$order->id)->with("sku")->get();
                    if ($sku->count()>0){
                        foreach ($sku as $item){
                            $item->sku->sell_num = $item->sku_sell_num+$item->goods_num;
                            $item->sku->save();
                        }
                    }
                    //商品颜色增加销量
                    $color = OrderGoods::where("order_id",$order->id)->with("color")->get();
                    if ($color->count()>0){
                        foreach ($color as $item){
                            $item->color->sell_num = $item->color->sell_num+$item->goods_num;
                            $item->color->save();
                        }
                    }
                    DB::commit();

                    //消费记录修改
                    $bill = Bill::where("order_sn", $order_sn)->first();
                    if ($bill && $bill->status == 0) {
                        $bill->status = 1;
                        $bill->save();
                    }
//                //判断用户是否存在销售
//                if ($user->parent_id!=0){
//                    //增加积分
//                    $parent = User::find($user->parent_id);
//                    $parent->score = $parent->score + floor($total_fee/100/100);
//                    $parent->save();
//                    //记录积分变动
//                    $score = new UserScoreRecord();
//                    $score->user_id = $parent->id;
//                    $score->next_user_id = $user->id;
//                    $score->type = 3;
//                    $score->remark = $user->nickname."购买商品赠送";
//                    $score->status = 1;
//                    $score->save();
//                }
                }
            }else{
                //查询订单
                $order = RechargeOrder::where("order_sn",$order_sn)->first();
                Log::info($order);
                //充值套餐
                $recharge = Recharge::find($order->recharge_id);
                //查询用户
                $user = User::find($order->user_id);
                //查询系统信息
                $system = System::find(1);
                //判断订单金额是否等于支付金额
                if ($order->money != $total_fee/100){
                    $refund = Wxpay::refundPay();
                    //退款
                    $order = [
                        'transaction_id' => $transaction_id,
                        'out_refund_no' => $order_sn,
                        'total_fee' => $total_fee, // **单位：分**
                        'refund_fee' => $total_fee,
                        "type" => 'miniapp',
                        'refund_desc' => '微信支付退款'
                    ];
                    //调用支付
                    Pay::wechat($refund)->refund($order);
                }else{
                    //开启事务
                    DB::beginTransaction();
                    //修改订单状态
                    $order->order_status = 1;
                    $order->is_paid = 1;
                    $order->paid_at = Carbon::now();
                    $order->save();

                    //修改用户积分
                    $user->score = $user->score+$recharge->score;
                    $user->recharge = $user->recharge+$recharge->money;
                    $user->save();

                    //修改支付记录
                    $ment = Wxpay::where("pay_sn",$order_sn)->first();
                    $ment->is_paid = 1;
                    $ment->transaction_id = $transaction_id;
                    $ment->amount = $total_fee / 100;
                    $ment->paid_at = Carbon::now();
                    $ment->save();

                    //修改消费记录
                    $bill = Bill::where("order_sn",$order_sn)->first();
                    if ($bill && $bill->status==0) {
                        $bill->status = 1;
                        $bill->save();
                    }

                    //判断销售是否存在
                    if ($user->sell_id){
                        $sell = User::find($user->sell_id);
                        if ($sell) {
                            //记录积分变动
                            $userScore = new UserScoreRecord();
                            $userScore->order_sn = $order_sn;
                            $userScore->user_id = $sell->id;
                            $userScore->next_user_id = $user->id;
                            $userScore->type = 1;
                            $userScore->score = $recharge->score*$system->sell_ratio;
                            $userScore->save();
                        }
                    }
                    if ($user->parent_id){
                        //查询积分变动记录
                        $userScore = UserScoreRecord::where("user_id",$user->parent_id)->where("next_user_id",$user->id)->first();
                        if (!$userScore){
                            $parent = User::find($user->parent_id);
                            if ($parent) {
                                //记录积分变动
                                $userScore = new UserScoreRecord();
                                $userScore->order_sn = $order_sn;
                                $userScore->user_id = $parent->id;
                                $userScore->next_user_id = $user->id;
                                $userScore->type = 1;
                                $userScore->score = $system->invit_ratio;
                                $userScore->save();
                            }
                        }
                    }

                    DB::commit();
                }

            }
            return $pay->success()->send();// laravel 框架中请直接 `return $pay->success()`
            //Log::debug('Wechat notify', $data->all());
        } catch (\Exception $e) {
            Log::error($e);
            DB::rollback();
            // $e->getMessage();
        }
    }


    //退款回调
    public function refund(){
        //支付参数赋值
        $wechat = Wxpay::refundPay();

        $pay = Pay::wechat($wechat);
        try{
            $xml = Request::createFromGlobals()->getContent();
            $array = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
            $data = $pay->verify($array['req_info'],true); // 是的，验签就这么简单！
            //$data = $pay->verify();

            //订单号
            $order_sn = $data['out_trade_no'];

            $header = substr($order_sn,0,2);
            if ($header!='cz') {
                //修改订单状态
                $order = Order::where("order_sn", $order_sn)->first();
                $order->order_status = 7;
                $order->refund_time = Carbon::now();
                $order->save();

                //消费记录
                $bill = new Bill();
                $bill->order_sn = $order_sn;
                $bill->userid = $order->userid;
                $bill->money = $order->pay_amount;
                $bill->type = 1;
                $bill->status = 1;
                $bill->save();
            }else{
                //修改订单状态
                $order = RechargeOrder::where("order_sn", $order_sn)->first();
                $order->order_status = 7;
                $order->save();

                //消费记录
                $bill = new Bill();
                $bill->order_sn = $order_sn;
                $bill->userid = $order->userid;
                $bill->money = $order->pay_amount;
                $bill->type = 1;
                $bill->status = 1;
                $bill->save();
            }
        } catch (\Exception $e) {
            // $e->getMessage();
        }

        return $pay->success();// laravel 框架中请直接 `return $pay->success()`

    }

}
